package com.hzcx.app.simplechat.ui.chat.adapter;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.util.glide.GlideUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChatSearchMsgAdapter extends BaseQuickAdapter<EMMessage, BaseViewHolder> {

    private String head;
    private String nickName;
    private String key;

    public ChatSearchMsgAdapter(int layoutResId, @Nullable List<EMMessage> data, String head, String nickName) {
        super(layoutResId, data);
        this.head = head;
        this.nickName = nickName;
    }

    @Override
    protected void convert(BaseViewHolder helper, EMMessage item) {

        EMTextMessageBody txtBody = (EMTextMessageBody) item.getBody();

        GlideUtils.loadImg(mContext, head, helper.getView(R.id.iv_head));
        helper.setText(R.id.tv_nick_name, nickName);

        String str=txtBody.getMessage();
        Pattern p = Pattern.compile(key);
        Matcher m = p.matcher(str);
        String s="";
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            if(start>7){
                s="..."+str.substring(start-7,start)+key;
            }else {
                s=str.substring(0,start)+key;
            }
            if(str.length()-end>7){
                s=s+str.substring(end,end+7)+"...";
            }else {
                s=s+str.substring(end);
            }
        }

        helper.setText(R.id.tv_content, findSearch(mContext.getResources().getColor(R.color.color_2D7CFD), s, key));

    }

    public void setKey(String key) {
        this.key = key;
    }

    /**
     * 关键字高亮变色
     *
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return
     */
    public static SpannableString findSearch(int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        Pattern p = Pattern.compile(keyword);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return s;
    }

}
